<html>
<head>
<script>
	
var newTabUrl = "";

var blackListUrls = new Array();	

chrome.tabs.onCreated.addListener(function(tab) {	
	newTabUrl = tab.url;
	
	// is new tab in blacklist?
	for (a in blackListUrls) {
		if (newTabUrl == blackListUrls[a]) {			
			// we got a match, now let's check to see if we already have one of those tabs open
			chrome.tabs.getAllInWindow(null, inspectTabs);
		}
	}
});


function inspectTabs (tabs) {
	var duplicates = new Array();
	
	for (a in tabs) {
		if (tabs[a].url == newTabUrl) {
			duplicates.push(tabs[a]);
		}
	}
	
	if (duplicates.length > 1) {
		for (b=0; b<duplicates.length-1; b++) {
			chrome.tabs.remove(duplicates[b].id)
		}
	}
	
}

function init() {

  chrome.browserAction.setBadgeBackgroundColor({color:[208, 0, 24, 255]});
  chrome.browserAction.setIcon({path: "tab.png"});
  
  blackListUrls = localStorage.getItem("blackListUrls").split(";");
  
}


chrome.tabs.onSelectionChanged.addListener(function(tabId, selectedInfo) {
	// checking to see if our selected tab is in the blacklist
	// if it is we'll change the browser action icon to indicate that the 
	// tab is blacklisted
	
	chrome.tabs.get(tabId, function(tab) {
		
		var index = isUrlInBlackList(tab.url);
		
		if ( index > -1) {
			 chrome.browserAction.setIcon({path: "tabBlocked.png"});
		}
		else
		{
			 chrome.browserAction.setIcon({path: "tab.png"});
		}
	});
});

// Called when the user clicks on the browser action.
chrome.browserAction.onClicked.addListener(function(tab) {
  
  
  var index = isUrlInBlackList(tab.url);
		
  if ( index > -1) {
  	chrome.browserAction.setIcon({path: "tab.png"});
	blackListUrls.splice(index, 1);

  }
  else 
  {
  	chrome.browserAction.setIcon({path: "tabBlocked.png"});
	// add to blacklist
  
    blackListUrls.push(tab.url);
  }
  
  localStorage.setItem("blackListUrls", blackListUrls.join(";"));
 
});

	function isUrlInBlackList(url) {
		
		for (a in blackListUrls) {
			if (url == blackListUrls[a]) {
				return a;
			}
		}
		return -1;
	}




</script>
</head>
<body onload="init()">
<img id="tab" src="tab.png">

</body>
</html>
